package com.lims.novel;

import com.lims.utils.FileUtil;
import org.junit.platform.commons.util.StringUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @author limaosheng
 * @create 2022-04-06 9:41
 * @desc
 */
public class ShenZang {
    //地址
    public final static String URL = "http://www.shenzang.org/read/";

    /**
     * @author lmshe
     * @create 20:46 2018/8/22
     * @desc 获取小说主要信息
     */
    public static NovelDto getNovelMsg(String serialNum) {
        //获取网页html内容
        String date = getData(URL + serialNum + ".html");
        if (StringUtils.isBlank(date)) {
            System.out.println("获取小说章节信息失败");
            return null;
        }
        System.out.println("小说章节信息：" + date);
        //解析分割小说主体内容
        NovelDto novelDto;
        try {
            String str = date;
            //小说dto
            novelDto = new NovelDto();
            novelDto.setNovelName(serialNum);
            //解析分割章节内容
            List<NovelChapterDto> NovelChapterList = new ArrayList<>();
            //切割list
            str = str.substring(str.indexOf("class=\"nav clearfix\"") + "class=\"nav clearfix\"".length(), str.indexOf("<script>index();</script>"));
            str = str.substring(str.indexOf("<span>") + "<span>".length(), str.lastIndexOf("</span>"));
            String[] chapterArr = str.split("</span>");
            //遍历
            for (String s : chapterArr) {

                String chapterStr = s;
                //编号
                String chapterSerialNum = chapterStr.substring(chapterStr.indexOf(serialNum + "/") + (serialNum + "/").length(), chapterStr.indexOf(".html"));
                //章节名
                chapterStr = chapterStr.substring(chapterStr.indexOf(".html") + ".html".length());
                String chapterName = chapterStr.substring(chapterStr.indexOf(">") + ">".length(), chapterStr.indexOf("</a>"));
                //加入列表
                NovelChapterDto novelChapterDto = new NovelChapterDto();
                novelChapterDto.setChapterName(chapterName);
                novelChapterDto.setChapterSerialNum(chapterSerialNum);
                NovelChapterList.add(novelChapterDto);
            }
            novelDto.setNovelChapterList(NovelChapterList);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return novelDto;
    }

    /**
     * @author lmshe
     * @create 17:58 2018/8/23
     * @desc 获取章节内容 http://xx/14_14055/9194140.html
     */
    public static String getChapterContent(String serialNum, String chapterSerialNum) {
        String chapterContent = "";
        //获取网页html内容
        String date = getData(URL + serialNum + "/" + chapterSerialNum + ".html");
        if (StringUtils.isNotBlank(date)) {
            try {
                String str = date.substring(date.indexOf("<div id=\"content\" class=\"content\"") + "<div id=\"content\" class=\"content\"".length());
                chapterContent = str.substring(0, str.indexOf("<div"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        chapterContent = chapterContent.replaceAll(" ", "");
        chapterContent = chapterContent.replaceAll("&nbsp;&nbsp;&nbsp;&nbsp;", "\n");
        chapterContent = chapterContent.replaceAll("<br/>", "");
        return chapterContent;
    }

    /**
     * @author lmshe
     * @create 20:38 2018/8/22
     * @desc 模拟浏览器发出请求，并返回网页内容字符串
     */
    public static String getData(String urlStr) {
        StringBuilder result = new StringBuilder();
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setInstanceFollowRedirects(true);
            conn.setRequestProperty("content-type", "text/html");
            conn.connect();
            InputStream is = conn.getInputStream();//拿到输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(is, "GBK"));
            String tempLine;
            while ((tempLine = br.readLine()) != null) {
                result.append(tempLine);
            }
            br.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    public static class NovelChapterDto {
        /**
         * 章节名
         */
        private String chapterName;
        /**
         * 章节编号
         */
        private String chapterSerialNum;

        public String getChapterName() {
            return chapterName;
        }

        public void setChapterName(String chapterName) {
            this.chapterName = chapterName;
        }

        public String getChapterSerialNum() {
            return chapterSerialNum;
        }

        public void setChapterSerialNum(String chapterSerialNum) {
            this.chapterSerialNum = chapterSerialNum;
        }
    }

    public static class NovelDto {
        /**
         * 作者
         */
        private String author;
        /**
         * 小说名称
         */
        private String novelName;
        /**
         * 简介
         */
        private String Introduction;
        /**
         * 最后更新时间
         */
        private String lastUpdateTime;
        /**
         * 章节列表
         */
        private List<NovelChapterDto> NovelChapterList;

        public String getAuthor() {
            return author;
        }

        public void setAuthor(String author) {
            this.author = author;
        }

        public String getNovelName() {
            return novelName;
        }

        public void setNovelName(String novelName) {
            this.novelName = novelName;
        }

        public String getIntroduction() {
            return Introduction;
        }

        public void setIntroduction(String introduction) {
            Introduction = introduction;
        }

        public void setLastUpdateTime(String lastUpdateTime) {
            this.lastUpdateTime = lastUpdateTime;
        }

        public List<NovelChapterDto> getNovelChapterList() {
            return NovelChapterList;
        }

        public void setNovelChapterList(List<NovelChapterDto> novelChapterList) {
            NovelChapterList = novelChapterList;
        }
    }

    public static void main(String[] args) {
        //小说编号
        String serialNum = "66444";
        NovelDto novelDto = getNovelMsg(serialNum);
        //生成小说目录
        String path = System.getProperty("user.dir") + "/log/" + novelDto.getNovelName();
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        int i = 1;
        for (NovelChapterDto dto : novelDto.getNovelChapterList()) {
            String chapterContent = getChapterContent(serialNum, dto.getChapterSerialNum());
            StringBuilder sb = new StringBuilder();
            sb.append(dto.getChapterName());
            sb.append(chapterContent);
            sb.append("\n");
            try {
                String resPath = path + "/第." + i + "章." + dto.getChapterName() + ".txt";
                System.out.println("文件地址：" + resPath);
                FileUtil.write(resPath, sb.toString());
            } catch (Exception e) {
                System.out.println("生成失败");
            }
            i++;
        }

    }
}
